/**
 * @(#)QRCodeUtil.java
 * @author liangcheng
 * @version 1.0 2016年7月27日
 * <p>
 * Copyright (C) 2000,2016 , TeamSun, Inc.
 */
package com.nuanshui.framework.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.nuanshui.framework.res.ResourceFacade;
import com.nuanshui.framework.res.UploadRequest;
import com.nuanshui.framework.res.qiniu.UpLoadFileVO;
import com.nuanshui.heatedloan.enums.FileBelong;
import org.springframework.beans.factory.annotation.Autowired;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 *
 * Purpose: 生成二维码
 *
 * @author liangcheng
 * @see
 * @since 6.1.0
 */

/**
 * @author svenl
 *
 */
public class QRCodeUtil {
    @Autowired
    public ResourceFacade resouceFacade;

    FileBelong belong = FileBelong.PRODUCT;

    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * 生成普通二维码
     * @return
     */
    public UpLoadFileVO generateQRCode(String content) {
        int width = 1000; // 图像宽度
        int height = 1000; // 图像高度
        String format = "png";// 图像类型
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        BitMatrix bitMatrix = null;
        try {
            // 生成矩阵
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //输出字节流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            MatrixToImageWriter.writeToStream(bitMatrix, format, bos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //输入字节流
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

        UpLoadFileVO vo = null;
        try {
            UploadRequest request = new UploadRequest();
            request.setInputStream(bis);
            vo = resouceFacade.uploadFile(request).getFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;

    }


    /**
     * 解析二维码
     */
    public void DecodeQRCode() {
        String filePath = "D://zxing.png";
        BufferedImage image;
        try {
            image = ImageIO.read(new File(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
            Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
            String content = result.getText();
            System.out.println("图片中内容：  " + content);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成带Logo的二维码
     * @param url
     * @return
     */
    public UpLoadFileVO generateLogoQRCode(String url) {
        String logoPath = "http://7xinj3.com2.z0.glb.qiniucdn.com/logo2.png";
        String format = "png";
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 1000, 1000, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        //写入流中  获得输入流
        ByteArrayInputStream bais = QRCodeUtil.writeToStream(bitMatrix, format, logoPath);

        UpLoadFileVO vo = null;
        try {
            UploadRequest request = new UploadRequest();
            request.setInputStream(bais);
            vo = resouceFacade.uploadFile(request).getFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vo;

    }

    private static ByteArrayInputStream writeToStream(BitMatrix matrix, String format, String logoPath) {

        BufferedImage image = toBufferedImage(matrix);
        Graphics2D gs = image.createGraphics();

        //载入logo
        URL logoURL = null;
        try {
            logoURL = new URL(logoPath);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        //读取logo
        Image img = null;
        try {
            img = ImageIO.read(logoURL);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //将logo写入 位图矩阵  大小为170*170
        gs.drawImage(img, 415, 415, 170, 170, null);
        gs.dispose();
        img.flush();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, format, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        return bais;
    }

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }


}


/**
 * Revision history
 * -------------------------------------------------------------------------
 *
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2016年7月27日 Sven创建版本
 */